
package xj.app;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*; 
import javax.imageio.*;

public class WindowClosingAnimation 
  extends AnimationPane { 

  public WindowClosingAnimation(JFrame frame) { 
    super(frame);
  }

  public void setStartComponent(JComponent start) {
    if (start != null) { 
      Component parent = start.getParent();
      r1 = start.getBounds();
      Point p0 = new Point(r1.x, r1.y);
      SwingUtilities.convertPointToScreen(p0, parent);
      r1.x = p0.x;
      r1.y = p0.y;
      //System.out.println("WindowClosingAnimation r1=" + r1); 
      if (robot != null) {
	img = robot.createScreenCapture(r1);
      }
    }
  }

  public void setStartComponent(JFrame start) {
    if (start != null) { 
      r1 = start.getBounds();
      if (robot != null) {
	img = robot.createScreenCapture(r1);
      }
    }
  }

  public void setEndComponent(JComponent end) {
    this.end = end;
    if (end != null) { 
      Component parent = end.getParent();
      r2 = end.getBounds();
      Point p0 = new Point(r2.x, r2.y);
      SwingUtilities.convertPointToScreen(p0, parent);
      r2.x = p0.x;
      r2.y = p0.y;
      //System.out.println("WindowClosingAnimation r2=" + r2); 
    }
  }

  public void start() {
    //System.out.println("WindowClosingAnimation.start()");
 
    if (frame != null) { 
      frame.setGlassPane(this); 
      setVisible(true);
      blockInput();

      Point p1 = new Point(r1.x, r1.y); 
      Point p2 = new Point(r2.x, r2.y); 
      Component parent = getParent(); 
      SwingUtilities.convertPointFromScreen(p1, parent);
      SwingUtilities.convertPointFromScreen(p2, parent);
      r1.x = p1.x;
      r1.y = p1.y;
      dx = (p2.x - p1.x) / num; 
      dy = (p2.y - p1.y) / num;       
      dw = (20 - r1.width) / num;
      dh = (20 - r1.height) / num;

      Thread runner = new Thread(new Runnable() {
	  public void run() { 
	    try { 
	      for (int i = num; i >= 0; i--) { 
		repaint();
		r1.x += dx;
		r1.y += dy;
		r1.width += dw;
		r1.height += dh;
		Thread.currentThread().sleep(delay);
	      }
	    } catch (InterruptedException e) {}
	    SwingUtilities.invokeLater(new Runnable() { 
		public void run() { 
		  setVisible(false); 
		}
	      });
	  }
	});
      runner.start(); 
    }
  }

  @Override
  public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON);
    AlphaComposite alpha = AlphaComposite.SrcOver.derive(0.5f);
    Composite composite = g2.getComposite();
    g2.setComposite(alpha);

    g2.setColor(Color.gray);
    g2.drawRect(r1.x, r1.y, r1.width, r1.height);
    if (img != null) { 
      g2.drawImage(img, r1.x, r1.y, r1.width, r1.height, null);
    }
  }

  Rectangle r1, r2;
  BufferedImage img; 
  JComponent end; 
  int dx, dy, dw, dh; 
  int num = 10; 
  int delay = 50;

}